package com.atuguigu.gmall.cart.controller;

import com.atuguigu.gmall.cart.config.JwtProperties;
import com.atuguigu.gmall.cart.interceptor.LoginInterceptor;
import com.atuguigu.gmall.cart.pojo.Cart;
import com.atuguigu.gmall.cart.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@Controller
public class CartController {

    @Autowired
    private CartService cartService;

    /*
    * 新增购物车，新增成功之后重定向到成功页面
    * */

    @GetMapping
    public String addCart(Cart cart){
        this.cartService.addCart(cart);
        return "redirect:http://cart.gmall.com/addCart.html?skuId=" + cart.getSkuId() + "&count" + cart.getCount();
    }

    /*
    * 新增购物车成功之后的回显方法
    * */
    @GetMapping("addCart.html")
    public String queryCart(Cart cart, Model model){
        BigDecimal count = cart.getCount();     //加入购物车时的数量
        cart = this.cartService.queryCart(cart.getSkuId());    //查询数据库之后的购物车
        cart.setCount(count);
        model.addAttribute("cart",cart);
        return "addCart";
    }

    @GetMapping("cart.html")
    public String queryCarts(Model model){
        List<Cart> cartList = this.cartService.queryCarts();
        model.addAttribute("carts",cartList);
        return "cart";
    }

    @GetMapping("test")
    @ResponseBody
    public String test(HttpServletRequest request){
        long now = System.currentTimeMillis();
        System.out.println("1 controller方法开始执行..................");

        this.cartService.execute1();
        this.cartService.execute2();

        /*future1.addCallback(result -> {
            System.out.println("execute1异步任务执行成功：" + result);
        },ex -> {
            System.out.println("7 execute1异步任务执行失败：" + ex.getMessage());
        });
        future2.addCallback(result -> {
            System.out.println("6 execute2异步任务执行成功：" + result);
        },ex -> {
            System.out.println("execute2异步任务执行失败：" + ex.getMessage());
        });*/

        System.out.println("2 Controller方法执行完成，耗时：" + (System.currentTimeMillis() - now));

        return "hello Cart";
    }
}
